package top.atluofu.luofuecommerce.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.atluofu.common.utils.PageUtils;
import top.atluofu.common.utils.Query;

import top.atluofu.luofuecommerce.product.dao.CategoryDao;
import top.atluofu.luofuecommerce.product.entity.CategoryEntity;
import top.atluofu.luofuecommerce.product.service.CategoryBrandRelationService;
import top.atluofu.luofuecommerce.product.service.CategoryService;
import top.atluofu.luofuecommerce.product.vo.Catelog2Vo;

/**
 * @author 有罗敷的马同学
 * @description impl
 * @Date 21:24 2022-11-16
 * @Param none
 * @Return none
 **/

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1. 查出所有分离
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        // 2. 组装成树形分类
        return categoryEntities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).map(menu -> {
            menu.setChildren(getChildren(menu, categoryEntities));
            return menu;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 检查
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> path = new ArrayList<>();
        path = findParentPath(catelogId, path);
        Collections.reverse(path);
        return path.toArray(new Long[path.size()]);
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "category",allEntries = true)
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Cacheable(value = {"category"}, key = "#root.method.name", sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categories() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    @Cacheable(value = "category", key = "#root.methodName")
    @Override
    public Map<String, List<Object>> getCatelogJson() {
        String catelogJSON = (String) redisTemplate.opsForValue().get("catelogJSON");
        if (StringUtils.isEmpty(catelogJSON)) {
            return getCatelogJsonFormDBWithRedissionLock();
        }
        return JSON.parseObject(catelogJSON, new TypeReference<Map<String, List<Object>>>() {
        });
    }

    public Map<String, List<Object>> getCatelogJsonFormDBWithRedissionLock() {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("catelogJson-lock");
        RLock rLock = readWriteLock.readLock();
        Map<String, List<Object>> dataFromDb = null;
        try {
            rLock.lock();
            dataFromDb = getCatelogJsonFromDb();
        } finally {
            rLock.unlock();
        }
        return dataFromDb;
    }

    public Map<String, List<Object>> getCatalogJsonFromDbWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            Map<String, List<Object>> dataFromDb;
            try {
                dataFromDb = getCatelogJsonFromDb();
            } finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] thenreturn redis.call('del', KEYS[1]) else return 0 end";
                Long lock1 = (Long) redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }
            return dataFromDb;
        } else {
            System.out.println("获取分布式锁失败...等待重试");
            try {
                Thread.sleep(200);
            } catch (Exception e) {

            }
            return getCatalogJsonFromDbWithRedisLock();
        }
    }


    public Map<String, List<Object>> getCatelogJsonFromDb() {
        synchronized (this) {
            String catelogJSON = (String) redisTemplate.opsForValue().get("catelogJSON");
            if (!StringUtils.isEmpty(catelogJSON)) {
                return JSON.parseObject(catelogJSON, new TypeReference<Map<String, List<Object>>>() {
                });
            }
            List<CategoryEntity> level1Categories = getLevel1Categories();
            return level1Categories.stream().collect(Collectors.toMap(k -> {
                return k.getCatId().toString();
            }, v -> {
                List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getParentCid()));
                List<Object> parent_cid = null;
                if (categoryEntities != null) {
                    parent_cid = categoryEntities.stream().map(item -> {
                        List<CategoryEntity> categoryEntities1 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", item.getCatId()));
                        List<Object> collect1 = null;
                        if (categoryEntities1 != null) {
                            collect1 = categoryEntities1.stream().map(item3 -> {
                                return new Catelog2Vo.catelog3Vo(item.getCatId().toString(), item3.getName(), item3.getCatId().toString());
                            }).collect(Collectors.toList());
                        }
                        return new Catelog2Vo(v.getCatId().toString(), collect1, item.getCatId().toString(), item.getName());
                    }).collect(Collectors.toList());
                }
                String s = JSON.toJSONString(parent_cid);
                redisTemplate.opsForValue().set("catelogJSON", s, 1, TimeUnit.DAYS);
                return parent_cid;
            }));
        }
    }

    private List<Long> findParentPath(Long catelogId, List<Long> path) {
        path.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), path);
        }
        return path;
    }

    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> categoryEntities) {
        return categoryEntities.stream().filter(categoryEntity -> {
            return Objects.equals(categoryEntity.getParentCid(), root.getCatId());
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildren(categoryEntity, categoryEntities));
            return categoryEntity;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
    }

}